package com.weijianhuawen.wjblog.common.utils;

import com.weijianhuawen.wjblog.common.config.MinioProperties;
import com.weijianhuawen.wjblog.common.enums.ResponseCodeEnum;
import com.weijianhuawen.wjblog.common.exception.BizException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: Minio 工具类
 * @date: 2024-10-23 19:18
 */

@Component
@Slf4j
public class MinioUtil {
    @Resource
    private MinioProperties minioProperties;

    @Resource
    private MinioClient minioClient;

    //上传文件
    public String uploadFile(MultipartFile file) throws Exception {
        //判断所传文件是否为空
        if (file == null || file.getSize() == 0) {
            log.warn("【文件上传错误】 上传文件不能为空");
            throw new BizException(ResponseCodeEnum.UPLOAD_FILE_IS_NULL_ERROR);
        }

        //文件原始名称
        String originFileName = file.getOriginalFilename();
        if (originFileName == null || "".equals(originFileName)) {
            log.warn("【文件上传异常】疑似损毁文件");
            throw new BizException(ResponseCodeEnum.UPLOAD_FILE_IS_PROBLEM_ERROR);
        }
        //文件类型
        String contentType = file.getContentType();

        // 生成储存对象的名称，使用uuid保证其名字唯一
        String key = UUID.randomUUID().toString().replace("-", "");

        //获取文件后缀
        String suffix = originFileName.substring(originFileName.lastIndexOf("."));

        //拼接文件名
        String uploadFileName = String.format("%s%s", key, suffix);
        log.info("【文件上传中】 文件：{} 正在上传", uploadFileName);

        //上传到Minio
        minioClient.putObject(PutObjectArgs.builder()
                        .bucket((minioProperties.getBucketName()))
                        .object(uploadFileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(contentType)
                        .build());

        //返回文件访问链接
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), uploadFileName);

        log.info("【文件上传成功】文件 {} 上传至Minio成功， 访问路径：{}", originFileName, url);
        return url;
    }
}
